<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
const pageTabsIndex = ref(1)
function clickPageTabs(index:number){
    pageTabsIndex.value = index
    PageNum.value = 1
    selectedRowIds.value.clear();
    postDeviceTEnvmonitor()
}

const faultIndex = ref(1)
function clickFault(index: number) {
    faultIndex.value = index
    PageNum.value = 1
    postDeviceTEnvmonitor()
}

//table-list
const tableHeight = ref(0)
// 定义表格数据的类型
interface TableRow {
    deviceId: number;
}
const listTableData = ref<any>([])
const listTableData1 = ref<any>([])
// 保存选中项的 ID 列表
const selectedRowIds = ref<Set<number>>(new Set());

// 处理选中项变化的函数
const handleSelectionChange = (selection: TableRow[]) => {
    // 更新选中项 ID 列表
    selectedRowIds.value = new Set(selection.map((item) => item.deviceId));
    console.log(selectedRowIds.value)
};

// 自定义行类名的函数
const rowClassName = ({ row }: { row: TableRow }): string => {
    return selectedRowIds.value.has(row.deviceId) ? 'selected-row' : '';
};
onMounted(() => {
    // 获取页面高度
    tableHeight.value = window.innerHeight - 300;
});

// 新增
const addDialogVisible = ref(false)
const addDialogVisible0 = ref(false)
const addForm = ref({
    parentGroupId: 1,
    deviceType: '',
    deviceName: '',
    deviceCode: '',
    status: '',
    devicePosition: '',
    remark:'',
})
const addForm0 = ref({
    parentGroupId: 0,
    bunkerName: '',
    deviceType: '',
    deviceName: '',
    deviceCode: '',
    deviceParentCode: '',
    ip: '',
    port: '',
    status: '',
    displayOrder: '',
    lon: '',
    lat: '',
    devicePosition: '',
    remark:'',
    parentBunkerId: ''
})

const handleDialogVisible = ref(false)


import { DictDataType, SystemDeviceTEnvmonitor, addDeviceTEnvmonitor, delDeviceTEnvmonitor, GetAllBunkerData, editDeviceTEnvmonitor } from "@/api";

// 设备状态
const deviceStatus = ref<any>([])
const smkcDeviceTypeData = ref<any>([])
const deviceTypeData = ref<any>([])
const getDictDataType = () => {
    DictDataType('device_status').then(res=>{
        console.log('设备状态-------',res.data)
        deviceStatus.value = res.data
    })
    DictDataType('smkc_device_type').then(res=>{
        console.log('程控设备类型-------',res.data)
        smkcDeviceTypeData.value = res.data
    })
    DictDataType('device_type').then(res=>{
        console.log('煤场设备类型-------',res.data)
        deviceTypeData.value = res.data
    })
}

// 煤场
const bunkerData = ref<any>([])
const getGetAllBunkerData = () => {
    GetAllBunkerData().then(res=>{
        console.log('BunkerData-------',res.data)
        bunkerData.value = res.data
    })
}


const PageNum = ref(1)
const PageSize = ref(10)
const totalPage = ref(0)
//list
const postDeviceTEnvmonitor = () => {
    SystemDeviceTEnvmonitor({
        GroupId: pageTabsIndex.value,
        Status: faultIndex.value,

        PageNum: PageNum.value,
        PageSize: PageSize.value
    }).then(res=>{
        console.log('list-------',res.data)
        listTableData.value = res.data.result
        totalPage.value =  res.data.totalNum
    })
}

// 删除
const clickDelDeviceTEnvmonitor = (id:any) => {
    ElMessageBox.confirm(
        '是否确定删除，删除后不能恢复?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
    .then(() => {
        delDeviceTEnvmonitor(id).then(res=>{
            console.log('删除----',res)
            if(res.code === 200){
                ElMessage({
                    type: 'success',
                    message: '已成功删除',
                })
                postDeviceTEnvmonitor()
            }
            else{
                ElMessage.error('删除失败，请重新删除')
            }
        })
    })
}


// 批量删除
const batchDel = () => {
    if(selectedRowIds.value.size == 0){
        ElMessage.error('请先选择要批量删除的数据')
    }
    else{
        const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
        })
        let ids: string = Array.from(selectedRowIds.value).join(', ');
        delDeviceTEnvmonitor(ids).then(res=>{
            console.log('删除----',res)
            loading.close()
            if(res.code === 200){
                ElMessage({
                    type: 'success',
                    message: '已成功删除',
                })
                postDeviceTEnvmonitor()
            }
            else{
                ElMessage.error('删除失败，请重新删除')
            }
        })
    }
}

//添加
const clickAddDeviceTEnvmonitor = () => {
    console.log(addForm.value)
    const postData = ref<any>({})
    if(pageTabsIndex.value == 1){
        postData.value = addForm.value
    }
    else if(pageTabsIndex.value == 0){
        postData.value = addForm0.value
    }
    addDeviceTEnvmonitor(postData.value).then(res=>{
        console.log('新增----',res)
        if(res.code === 200){
            ElMessage({
                type: 'success',
                message: '添加成功',
            })
            addDialogVisible.value = false
            addDialogVisible0.value = false
            postDeviceTEnvmonitor()
        }
        else{
            ElMessage.error(res.msg)
        }
    })
}



const ruleFormRef1 = ref<FormInstance>()
const ruleFormRef0 = ref<FormInstance>()
const rulesForm = ref({
    deviceCode: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    deviceName: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    deviceType: [
        { required: true, message: '请选择', trigger: 'change' },
    ],
    status: [
        { required: true, message: '请选择', trigger: 'change' },
    ],
    devicePosition: [
        {  message: '请选择', trigger: 'change' },
    ],
    remark:[
        {  message: '请选择', trigger: 'change' },
    ]
})

const rulesForm0 = ref({
    deviceCode: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    deviceName: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    deviceType: [
        { required: true, message: '请选择', trigger: 'change' },
    ],
    status: [
        { required: true, message: '请选择', trigger: 'change' },
    ],
    parentBunkerId: [
        { required: true, message: '请输入', trigger: 'blur' },
    ],
    displayOrder: [
        { required: true, message: '请输入', trigger: 'blur' },
    ]
})

const submitAddForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            clickAddDeviceTEnvmonitor()
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetAddForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const submitAddForm0 = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            clickAddDeviceTEnvmonitor()
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetAddForm0 = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const isEdit = ref(false)

//修改
const postEditDeviceTEnvmonitor = (itemForm:any) => {
    console.log('editForm----',itemForm)
    isEdit.value = true
    if(pageTabsIndex.value == 1){
        addForm.value = itemForm
        addForm.value.status = itemForm.status.toString()
        addDialogVisible.value = true
    }
    else if(pageTabsIndex.value == 0){
        addForm0.value = itemForm
        addForm0.value.status = itemForm.status.toString()
        addDialogVisible0.value = true
    }
    
}

// 修改
const submitEditForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            clickEditDeviceTEnvmonitor()
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 修改
const submitEditForm0 = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            clickEditDeviceTEnvmonitor()
        } else {
            console.log('error submit!', fields)
        }
    })
}


//修改
const clickEditDeviceTEnvmonitor = () => {
    console.log(addForm.value)
    const postData = ref<any>({})
    if(pageTabsIndex.value == 1){
        postData.value = addForm.value
    }
    else if(pageTabsIndex.value == 0){
        postData.value = addForm0.value
    }
    editDeviceTEnvmonitor(postData.value).then(res=>{
        console.log('修改----',res)
        if(res.code === 200){
            ElMessage({
                type: 'success',
                message: '修改成功',
            })
            addDialogVisible.value = false
            addDialogVisible0.value = false
            postDeviceTEnvmonitor()
        }
        else{
            ElMessage.error(res.msg)
        }
    })
}


onMounted(()=>{
    getDictDataType()
    getGetAllBunkerData()
    postDeviceTEnvmonitor()
    
})


</script>
<template>
    <!-- 弹出框/新增 -->
    <el-dialog v-model="addDialogVisible" :title="isEdit?'修改设备':'添加设备'" width="900" :align-center="true">
        <div class="dialog_main">
            <el-form ref="ruleFormRef1" :rules="rulesForm" :inline="true" :model="addForm" class="mt15 form-inline-row-two" label-width="auto">
                <el-form-item label="设备编码:" prop="deviceCode">
                    <el-input v-model="addForm.deviceCode" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="设备名称:" prop="deviceName">
                    <el-input v-model="addForm.deviceName" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="设备类型:" prop="deviceType">
                    <el-select v-model="addForm.deviceType" placeholder="请选择">
                        <el-option v-for="(item,index) in smkcDeviceTypeData" :key="index" :label="item.dictLabel" :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备状态:" prop="status">
                    <el-select v-model="addForm.status" placeholder="请选择">
                        <el-option v-for="(item,index) in deviceStatus" :key="index" :label="item.dictLabel" :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="安装位置:" prop="devicePosition"  style="width: 92%;">
                    <el-input v-model="addForm.devicePosition" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="设备描述:" prop="remark" style="width: 92%;">
                    <el-input v-model="addForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="请输入" />
                </el-form-item>
            </el-form>
            <!-- <el-form v-if="pageTabsIndex == 0" ref="ruleFormRef0" :inline="true" :model="addForm" class="mt15 form-inline-row-two" label-width="auto">
                <el-form-item label="所属煤场:">
                    <el-input v-model="addForm.bunkerName" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="设备名称:">
                    <el-input v-model="addForm.deviceName" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="设备类型:">
                    <el-select v-model="addForm.deviceType" placeholder="请选择">
                        <el-option v-for="(item,index) in deviceTypeData" :key="index" :label="item.dictLabel" :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备状态:">
                    <el-select v-model="addForm.status" placeholder="请选择">
                        <el-option v-for="(item,index) in deviceStatus" :key="index" :label="item.dictLabel" :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备编码:">
                    <el-input v-model="addForm.deviceCode" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="父设备编码:">
                    <el-input v-model="addForm.deviceParentCode" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="设备ip:">
                    <el-input v-model="addForm.ip" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="设备端口:" >
                    <el-input v-model="addForm.port" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="显示顺序:" >
                    <el-input v-model="addForm.displayOrder" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="经度:" >
                    <el-input v-model="addForm.lon" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="纬度:" >
                    <el-input v-model="addForm.lat" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="安装位置:" >
                    <el-input v-model="addForm.devicePosition" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="备注:" style="width: 92%;">
                    <el-input v-model="addForm.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="请输入" />
                </el-form-item>
            </el-form> -->
        </div>
        <template #footer>
            <div class="dialog-footer-center">
                <el-button v-if="isEdit" type="primary" color="#2565C8" style="width: 130px;" @click="submitEditForm(ruleFormRef1)">
                    修改
                </el-button>
                <el-button v-else type="primary" color="#2565C8" style="width: 130px;" @click="submitAddForm(ruleFormRef1)">
                    添加
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="addDialogVisible0" :title="isEdit?'修改设备':'添加设备'" width="900" :align-center="true">
        <div class="dialog_main">
            <el-form ref="ruleFormRef0" :rules="rulesForm0" :inline="true" :model="addForm0" class="mt15 form-inline-row-two" label-width="auto">
                <el-form-item label="所属煤场:" prop="parentBunkerId">
                    <el-select v-model="addForm0.parentBunkerId" placeholder="请选择">
                        <el-option v-for="(item,index) in bunkerData" :label="item.bunkerName" :value="item.bunkerId" :key="index" />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备名称:" prop="deviceName">
                    <el-input v-model="addForm0.deviceName" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="设备类型:" prop="deviceType">
                    <el-select v-model="addForm0.deviceType" placeholder="请选择">
                        <el-option v-for="(item,index) in deviceTypeData" :key="index" :label="item.dictLabel" :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备状态:" prop="status">
                    <el-select v-model="addForm0.status" placeholder="请选择">
                        <el-option v-for="(item,index) in deviceStatus" :key="index" :label="item.dictLabel" :value="item.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item label="设备编码:" prop="deviceCode">
                    <el-input v-model="addForm0.deviceCode" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="父设备编码:" prop="deviceParentCode">
                    <el-input v-model="addForm0.deviceParentCode" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="设备ip:" prop="ip">
                    <el-input v-model="addForm0.ip" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="设备端口:" prop="port">
                    <el-input v-model="addForm0.port" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="显示顺序:" prop="displayOrder">
                    <el-input v-model="addForm0.displayOrder" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="经度:" prop="lon">
                    <el-input v-model="addForm0.lon" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="纬度:" prop="lat">
                    <el-input v-model="addForm0.lat" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="安装位置:" prop="devicePosition">
                    <el-input v-model="addForm0.devicePosition" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="备注:" prop="remark" style="width: 92%;">
                    <el-input v-model="addForm0.remark" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="请输入" />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer-center">
                <el-button v-if="isEdit" type="primary" color="#2565C8" style="width: 130px;" @click="submitEditForm0(ruleFormRef0)">
                    修改
                </el-button>
                <el-button v-else type="primary" color="#2565C8" style="width: 130px;" @click="submitAddForm0(ruleFormRef0)">
                    添加
                </el-button>
            </div>
        </template>
    </el-dialog>

     <!-- 弹出框/处理 -->
     <!-- <el-dialog v-model="handleDialogVisible" title="处理" width="800" :align-center="true">
        <div class="dialog_main">
            <el-form :inline="true" :model="addForm" class="mt15 form-inline-row-two" label-width="60">
                <el-form-item label=" ">
                    <el-select v-model="addForm.name3" placeholder="请选择">
                        <el-option label="未解决" value="1" />
                        <el-option label="已解决" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注:" style="width: 92%;">
                    <el-input v-model="addForm.name5" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="请输入" />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer-center">
                <el-button type="primary" color="#2565C8" style="width: 130px;">
                    添加
                </el-button>
            </div>
        </template>
    </el-dialog> -->


    <div class="flex_bg">
        <ul class="page_tabs">
            <!-- <li v-for="(item,index) in pageTabsNav" @click="clickPageTabs(index)" :class="pageTabsIndex == index?'hover':''">{{ item }}</li> -->
            <li @click="clickPageTabs(1)" :class="pageTabsIndex == 1?'hover':''">输煤程控设备</li>
            <li @click="clickPageTabs(0)" :class="pageTabsIndex == 0?'hover':''">煤场设备</li>
        </ul>
        
        <div class="flex_between mt20">
            <div class="device_tabs">
                <div class="name">设备状态:</div>
                <ul>
                    <li v-for="(item, index) in deviceStatus"  :class="faultIndex == item.dictValue ? 'hover' : ''" :key="index"
                        @click="clickFault(item.dictValue)">
                        {{ item.dictLabel }}
                    </li>
                </ul>
            </div>
            <el-button type="primary" color="#2565C8" @click="batchDel">批量删除</el-button>
            <el-button v-if="pageTabsIndex == 1" type="primary" color="#2565C8" @click="addDialogVisible = true, resetAddForm(ruleFormRef1)">新增</el-button>
            <el-button v-if="pageTabsIndex == 0" type="primary" color="#2565C8" @click="addDialogVisible0 = true, resetAddForm(ruleFormRef0)">新增</el-button>
        </div>
        
        <!-- tab1 -->
        <el-table v-if="pageTabsIndex == 1"
                  class="mt20"
                  :data="listTableData"
                  size="large"
                  :border="false"
                  :stripe="false"
                  :highlight-current-row="false"
                  :height="tableHeight"
                  style="width: 100%;"
                  :row-class-name="rowClassName"
                  header-cell-class-name="table_big_th"
                  ref="multipleTableRef"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="right" />
            <el-table-column label="设备名称" prop="deviceName" />
            <el-table-column label="设备类型" prop="deviceType">
                <template #default="scope">
                    <span v-for="(item,index) in smkcDeviceTypeData" :key="index">
                        <span v-if="scope.row.deviceType == item.dictValue">{{ item.dictLabel }}</span>
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="当前状态" prop="status">
                <template #default="scope">
                    <span v-for="(item,index) in deviceStatus" :key="index">
                        <span v-if="scope.row.status == item.dictValue">{{ item.dictLabel }}</span>
                    </span>
                </template>
            </el-table-column>
            <el-table-column label="安装位置" prop="devicePosition" />
            <el-table-column label="设备编号" prop="deviceCode" />
            <el-table-column label="设备描述" prop="remark" />
            <el-table-column align="center" label="操作" min-width="120">
                <template #default="scope">
                    <div class="table_btn">
                        <a href="javascript:;" @click="postEditDeviceTEnvmonitor(scope.row)">修改</a>|
                        <a href="javascript:;" @click="clickDelDeviceTEnvmonitor(scope.row.deviceId)">删除</a>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- tab2 -->
        <el-table v-if="pageTabsIndex == 0"
            class="mt20"
            :data="listTableData" 
            size="large" 
            :border="false" 
            :stripe="false"
            :highlight-current-row="false" 
            :height="tableHeight" 
            style="width: 100%;" 
            :row-class-name="rowClassName"
            header-cell-class-name="table_big_th"
            ref="multipleTableRef" 
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="right" />
            <el-table-column label="所属煤场" prop="bunkerName" />
            <el-table-column label="设备名称" prop="deviceName" />
            <el-table-column label="设备类型" prop="deviceType" >
                <template #default="scope">
                    <span v-for="(item,index) in deviceTypeData" :key="index">
                        <span v-if="scope.row.deviceType == item.dictValue">{{ item.dictLabel }}</span>
                    </span> 
                </template>
            </el-table-column>
            <el-table-column label="设备状态" prop="status" >
                <template #default="scope">
                    <span v-for="(item,index) in deviceStatus" :key="index">
                        <span v-if="scope.row.status == item.dictValue">{{ item.dictLabel }}</span>
                    </span> 
                </template>
            </el-table-column>
            <el-table-column label="设备编号" prop="deviceCode" />
            <el-table-column label="父设备编号" prop="deviceParentCode" />
            <el-table-column label="设备ip" prop="ip" />
            <el-table-column label="设备端口" prop="port" />
            <el-table-column label="显示顺序" prop="displayOrder" />
            <el-table-column label="经度" prop="lon" />
            <el-table-column label="纬度" prop="lat" />
            <el-table-column label="安装位置" prop="devicePosition" />
            <el-table-column label="备注" prop="remark" />
            <el-table-column align="center" label="操作" min-width="120">
                <template #default="scope">
                    <div class="table_btn">
                        <a href="javascript:;" @click="postEditDeviceTEnvmonitor(scope.row)">修改</a>|
                        <a href="javascript:;" @click="clickDelDeviceTEnvmonitor(scope.row.deviceId)">删除</a>
                    </div>
                </template>
            </el-table-column>

        </el-table>

        <div class="pagination">
            <el-pagination v-model:current-page="PageNum" v-model:page-size="PageSize" @current-change="postDeviceTEnvmonitor" :total="totalPage"  background layout="prev, pager, next" />
        </div>

    </div>

</template>
<style scoped lang="scss">
::v-deep(.el-table__body-wrapper){
    background: #F6FAFE !important;
}
::v-deep(.el-table__inner-wrapper:before){
    display: none; //下边线
}
::v-deep(.el-table thead th) {
  color: #333 !important;
  background: #CCDDF9;
}
::v-deep(.el-table__body){
    border-spacing: 0px 13px !important;
}
::v-deep(.el-table__row td){
    border-top:1px solid #E0E5ED !important;
    border-bottom:1px solid #E0E5ED !important;
}
::v-deep(.el-table__row td:first-child){
    border-left:1px solid #E0E5ED !important;
}
::v-deep(.el-table__row td:last-child){
    border-right:1px solid #E0E5ED !important;
}
::v-deep(.el-table__row:hover td){
    background: #ecf5ff!important;
}
::v-deep(.el-table__expanded-cell){
    border:1px solid #E0E5ED !important;
    padding:0 !important;
    //border-top: none !important; 
}
// ::v-deep(.el-table__expanded-cell td){
//     background: #ecf5ff!important;
// }
::v-deep(.el-table__expanded-cell:hover) {
  background-color: #ecf5ff !important;
}
::v-deep(.el-table__row.selected-row td){
    background: #FFDE9A !important;
}

</style>